<template>
	<div class="pay-confirm">
		<group gutter="0.26rem" class="order-info">
			<h3 class="order-type">订单信息</h3>
			<cell class="order-master" v-if="$route.query.from == 'qa'" :title="orderData.question">
				<span class="red">￥{{orderData.totalMoney || '0.00'}}</span>
			</cell>
			<cell class="order-master" v-else>
				<img slot="icon" class="avatar" :src="orderData.masterPhoto | hasdomain">
				<p v-if="orderData.masterName">{{orderData.masterName + '-' + orderData.question}}</p>
				<span class="red">￥{{orderData.totalMoney || '0.00'}}</span>
			</cell>
			<cell title="订单编号" :value="orderData.orderNo"></cell>
			<cell title="下单时间" :value="orderData.createTime"></cell>
		</group>

    <p class="please">
			<mark>请添写测算人真实信息</mark>
      <span class="add" v-if="!isbazi" @click="newBazi('new')">新增</span>
		</p>
    <div class="bazi-list">
      <ul class="list">
        <li v-for="(v, i) in bazis" :key="'bz' + i" :class="{active: bazi.id == v.id}" @click="newBazi('add', v)">
					<span>{{v.name}}</span>
				</li>
      </ul>
    </div>
		<div class="more-space">加载更多</div>
		<transition name="slide">
			<div class="bazi_mark" v-if="isbazi">
				<group :key="bazi.id" gutter="0.26rem" label-width="4.1em" label-align="right" label-margin-right="1em" class="bazi-form bazi-slide mark_form">
					<x-input :readonly="!!bazi.id" title="真实姓名" placeholder="请输入姓名" v-model="bazi.name"></x-input>
					<selector :readonly="!!bazi.id" title="性别" placeholder="请选择性别" v-model="bazi.sex" value-text-align="left" :options="[{key: '1', value: '男'}, {key: '2', value: '女'}]"></selector>
					<datetime :readonly="!!bazi.id" title="出生日期" placeholder="请选择出生日期" clear-text="请选择出生日期" v-model="bazi.birth" value-text-align="left" :min-year="1900" :max-year="new Date().getFullYear()"></datetime>
					<popup-picker :disabled="!!bazi.id" title="出生时辰" placeholder="请选择出生时辰" popup-title="请选择出生时辰" v-model="bazi.birthTime" value-text-align="left" :data="birthTimes"></popup-picker>
					<x-address @on-shadow-change="shadowChange" :disabled="!!bazi.id" title="出生地点" placeholder="请选择出生地点" popup-title="请选择出生地点" v-model="bazi.areaName" :list="addressData" value-text-align="left"></x-address>
					<div class="please">
						<div class="please_btn">
							<span class="add" @click="isbazi = false">确认</span>
							<span class="add active" v-if="bazi.id == 0" @click="addBazi()">保存</span>
						</div>
					</div>
				</group>
			</div>
		</transition>
		
		<group gutter="0.26rem" label-width="4.5em" label-align="right" label-margin-right="1em" class="bazi-form">
			<x-input title="特殊说明" placeholder="特殊情况说明（10字以内）" v-model="bazi.content"></x-input>
		</group>
		<group gutter="0.26rem" label-width="7.1em" label-align="right" label-margin-right="1em" class="bazi-form">
			<popup-picker title="请选择三个数字" placeholder="请点击选择三个数字" popup-title="请选择三个数字" v-model="threeNumber" value-text-align="left" :data="threeNumbers"></popup-picker>
		</group>

		<group gutter="0.26rem" class="order-info">
			<h3 class="order-type">支付信息</h3>
			<cell title="订单金额">
				<span class="red">￥{{orderData.totalMoney || '0.00'}}</span>
			</cell>
			<cell title="优惠券" is-link @click.native="getCoupons">
				<span>{{orderData.couponName}}</span>
				<span class="red">-￥{{orderData.couponMoney || '0.00'}}</span>
			</cell>
			<cell title="实付金额">
				<span class="red">￥{{orderData.realMoney > 0 ? orderData.realMoney : '0.00'}}</span>
			</cell>
		</group>

		<!-- <group gutter="0.26rem" class="order-info">
			<cell title="开通黑卡会员减免">
				<span class="red">￥{{'-0.00'}}</span>
			</cell>
		</group> -->

		<group gutter="0.26rem" class="pay-list">
			<h3 class="order-type">支付方式</h3>
			<cell :title="v.payName" v-for="(v, i) in paysData" :key="'pay' + i" @click.native="payCode = v.payCode">
				<img slot="icon" :src="require('@/assets/login/'+ v.payCode +'@2x.png')" class="pay-logo">
				<icon :type="payCode == v.payCode ? 'success' : 'circle'"></icon>
			</cell>
		</group>
		
		<group gutter="0" class="order-pay">
			<x-button type="primary" :disabled="!payCode"  @click.native="bazi.id == 0 ? addBazi(orderPay) : orderPay()">确定支付</x-button>
		</group>

		<div v-transfer-dom>
      <popup v-model="couponShow">
        <div class="coupons">
          <div class="title">请选择优惠券</div>
          <div class="list vux-1px-tb">
            <ul>
              <li class="vux-1px-b" v-for="(v, i) in coupons" :key="'coupon' + i" :class="{active: coupon.couponUserId == v.couponUserId}" @click="coupon = v">
                <span>{{v.couponName}} （{{v.couponMoney == '101' ? '闪问免费' : '可优惠￥' + v.couponMoney}}）</span>
              </li>
            </ul>
          </div>
          <x-button type="primary" :disabled="!coupon.couponUserId" @click.native="selCoupon">确定</x-button>
        </div>
      </popup>
    </div>
		<div ref="confirm">
			
		</div>
	</div>
</template>

<script>
import {ChinaAddressV4Data} from "vux";
export default {
  data() {
    return {
			orderData: {},
			payCode: '',
			paysData: [],
			coupon: {},
			coupons: [],
			couponShow: false,
			bazis: [],
			bazi: {},
			addressData: ChinaAddressV4Data,
			threeNumber: [],
			dizhiName: [],
			isbazi: false,
			payData: {}
		};
	},
	computed: {
		uid() {
			return this.$store.state.userId;
		},
		oid() {
			return this.$route.query.id;
		},
    birthTimes() {
			let arr = [];
			arr.push('不清楚')
      for(var i = 0; i < 24; i++){
        let j = i < 10 ? '0' + i : i;
        arr.push(`${j}:00-${j}:59`);
      }
      return [arr];
		},
		threeNumbers() {
			let arr = [];
			for(var i = 1; i < 10; i++) {
				arr.push(i);
			}
			return [arr, arr, arr];
		}
	},
	methods: {
		shadowChange(a, b) {
			this.dizhiName = b
		},
		getBazilist() {
			this.$http.fetchGet('getBaziList', {
        userId: this.uid,
        all: 1,
			}).then(({data = []}) => {
        console.log('八字列表', data);
				this.bazis = data.map(v => {
					// v.areaName = v.areaName ? v.areaName.split(' ') : [];
					v.areaName = [v.areaId1, v.areaId2, v.areaId3]
          v.birthTime = v.birthTime ? [v.birthTime] : [];
          return v;
        });
			})
		},
    addBazi(callback) {
			console.log(this.bazi)
			if(!this.bazi.name) return this.$vux.toast.text('请输入姓名！');
			if(!this.bazi.sex) return this.$vux.toast.text('请选择性别！');
			if(!this.bazi.birth) return this.$vux.toast.text('请选择出生日期！');
			if(!this.bazi.birthTime) return this.$vux.toast.text('请选择出生时辰！');
			if(!this.bazi.areaName) return this.$vux.toast.text('请选择出生地点！');
      this.$http.fetchGet('baziadd', {
        userId: this.uid,
        id: this.bazi.id,
        name: this.bazi.name,
        sex: this.bazi.sex,
        areaId1: this.bazi.areaName[0],
        areaId2: this.bazi.areaName[1],
        areaId3: this.bazi.areaName[2],
        areaName: this.dizhiName.join(' '),
        birthday: this.bazi.birth,
        birthTime: this.bazi.birthTime[0],
        content: this.bazi.content,
			}).then(({data}) => {
        console.log('八字保存', data);
        this.$vux.toast.text('信息保存成功！');
				this.bazi.id = data;
				this.isbazi = false
				this.bazis.push(this.bazi);
				callback && callback();
			})
		},
		newBazi(type, item) {
			if (type == 'add') {
				this.isbazi = true
				this.bazi = item
			} else if(type == 'new') {
				this.bazi = {id: 0}
				this.isbazi = true
				this.bazi.id = 0
			}
		},
		getOrder() {
			this.$http.fetchGet('confirmServiceOrder', {
				userId: this.uid,
				orderId: this.oid,
				couponUserId: this.coupon.couponUserId ? this.coupon.couponUserId : this.$route.query.couponUserId,
			}).then(({data = {}}) => {
				console.log('确认订单', data);
				this.orderData = data;
				this.coupon = data
				console.log(this.coupon)
			})
		},
		getCoupons() {
			if(this.orderData.isLocked == 0) {
				this.$http.fetchGet('showCoupon', {
					userId: this.uid,
					orderId: this.oid,
					questionType: this.orderData.questionType,
				}).then(({data = []}) => {
					console.log('优惠券', data);
					this.coupons = data;
					this.couponShow = true;
				})
			}
		},
		selCoupon() {
			this.couponShow = false;
			this.$http.fetchGet('selectOneCoupon', {
				userId: this.uid,
				orderId: this.oid,
				couponUserId: this.coupon.couponUserId,
			}).then(({data = {}}) => {
				console.log('选择优惠券', data);
				this.coupon.reduceMoney = data.reduceMoney;
				this.getOrder();
			})
		},
		getPays() {
			this.$http.fetchGet('getPaymentList').then(({data = []}) => {
				console.log('支付方式', data);
				this.paysData = data;
			})
		},
		orderPay() {
			console.log(this.coupon)
			if(!this.bazi.id) return this.$vux.toast.text('请选择或新增测算人！');
			if(!Boolean(this.threeNumber.length)) return this.$vux.toast.text('请选择三个数字！');
			this.$http.fetchGet('pay', {
				userId: this.uid,
				orderId: this.orderData.orderId,
				payMethod: this.payCode,
				couponMoney: this.coupon.couponMoney,
				couponUserId: this.coupon.couponUserId,
				baziId: this.bazi.id,
				threeNumber: this.threeNumber.join(' '),
			}).then((data = {}) => {
				console.log('支付发起', data);
				this.payData = data
				if(!this.payData.hasOwnProperty('isPaid') && !this.payData.hasOwnProperty('data')) {
					this.payConfig = data;
					data.appId && this[this.payCode]();
					if(this.payCode == 'alipay') {
						// this.$refs.confirm.innerHTML = data
							// document.forms['alipaysubmit'];
							// console.log("alipaysubmit", document.forms['alipaysubmit'])
							// var btn = document.querySelector("input[type='submit']");
									
							// var queryParam = '';
							// Array.prototype.slice.call(document.querySelectorAll("input[type=hidden]")).forEach(function (ele, ind) {
							// 		queryParam += '&' + ele.name + "=" + encodeURIComponent(ele.value);
							// });
							// var gotoUrl = document.querySelector("#alipaysubmit").getAttribute('action') + '&' + queryParam;
							window.location.href = "/alipay?" + data
							// _AP.pay('https://openapi.alipay.com/gateway.do?' + data);
							return false;
					}
				}else {
					this.$emit('next', 'replace', {
						id: this.orderData.orderNo,
					});
				}
			})
		},
		wxpay() {
			if (typeof WeixinJSBridge === 'undefined') {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
					document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
				}
			} else {
				this.onBridgeReady()
			}
		},
		onBridgeReady() {
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				'appId': this.payConfig.appId,
				'timeStamp': this.payConfig.timeStamp,
				'nonceStr': this.payConfig.nonceStr,
				'package': this.payConfig.package,
				'signType': this.payConfig.signType,
				'paySign': this.payConfig.paySign
			}, (res) => {
				// alert('调试微信支付' + JSON.stringify(res));
				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					alert('微信支付成功');
					this.$emit('next', 'replace', {
						id: this.orderData.orderNo,
					});
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					alert('用户取消支付');
				} else if (res.err_msg === 'get_brand_wcpay_request:fail') {
					alert('网络异常，请重试');
				}
			})
		},
		alipay() {
			
		}
	},
	created() {
		this.getBazilist();
		this.getOrder();
		this.getPays();
	}
};
</script>

<style lang="less">
.pay-confirm {
	.weui-cell{
		.f26;
		.px2rem(min-height, 90);
    .padd(0, 23);
  }
  .vux-selector-readonly{
    text-align: left;
    color: inherit;
  }
  .vux-cell-value{
    color: #333333;
  }
}
</style>

<style scoped lang="less">
.pay-confirm{
	.order-type{
		.f30;
		.h(90);
		.pl(23);
		font-weight: normal;
		display: flex;
		align-items: center;
	}
	.order-master{
		.pt(18);
		.pb(18);
	}
	.order-info{
		.avatar{
			display: block;
			.ml(15);
			.w(70);
			.h(70);
			.bri(10);
			overflow: hidden;
		}
		.red{
			color: red;
		}
	}
	.order-pay{
		.p(20);
		background-color: #fff;
	}
	.pay-logo{
		display: block;
		.w(45);
		.mr(14);
	}
	
  .please{
		.f26;
		.h(90);
		.pl(20);
		.pr(20);
		display: flex;
		align-items: center;
		justify-content: space-between;
    .add{
			.w(100);
			.h(50);
			.lh(50);
			text-align: center;
      color: @primary;
			border: 1px solid @primary;
			.bri(10);
			transition: all 0.4s;
			&.active{
				color: #fff;
				background-color: @primary;
			}
    }
  }
  .bazi-list{
    .f26;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    .list{
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      .p(10);
      li{
				box-sizing: border-box;
				width: 25%;
				.lh(50);
        .p(10);
        text-align: center;
				span{
					display: block;
        	border: 1px solid @primary;
					.bri(10);
					transition: all 0.4s;
				}
        &.active span{
          color: #fff;
          background-color: @primary;
        }
      }
    }
	}
	.more-space{
		display: none;
		.h(20);
		text-align: center;
	}
	.bazi-slide{
		overflow: hidden;
		max-height: 10rem;
    &.slide-enter-active,
    &.slide-leave-active {
      transition: all 0.5s;
    }
    &.slide-enter,
    &.slide-leave-to {
      max-height: 0;
    }
	}
	.bazi_mark{
		position: fixed;
		top:0;
		left:0;
		width:100%;
		height:100%;
		background: rgba(0,0,0,.4);
		z-index: 99;
		.mark_form{
			position: absolute;
			bottom:0;
			left:0;
			right:0;
		}
		.please{
			.f26;
			.h(90);
			.pl(20);
			.pr(20);
			background:#fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.please_btn{
				position:absolute;
				right: 10px;
				.add{
					.w(120);
					.h(60);
					.lh(60);
					.ml(20);
					text-align: center;
					color: @primary;
					border: 1px solid @primary;
					.bri(10);
					transition: all 0.4s;
					display: inline-block;
					&.active{
						color: #fff;
						background-color: @primary;
					}
				}
			}
		}
	}
}
.coupons{
  .pl(20);
  .pr(20);
  .pb(20);
  background-color: #ffffff;
  .title{
    .f30;
    .lh(95);
    text-align: center;
  }
  .list{
    .mb(20);
    li{
      .h(84);
      .f28;
      color: #666666;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &.active{
        color: @primary;
      }
    }
  }
}
</style>
